<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="LAFDC.DataAccess" %>
<%@ Import Namespace="LAFDC.Logging" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script language="c#" runat="server">
	public static string source = "RoutageExport.aspx";

    protected void Page_Load(object sender, EventArgs e) {

	string logFile = "FAMCHEM.TXT";
	string logDir = "C:\\program files\\LAFDC\\LAFDCWeb\\Logging";
	string logPath = logDir + "\\" + logFile;

	if (!Directory.Exists(logDir)) {
		Directory.CreateDirectory(logDir);
	}

	// Check if the file exist before trying to write events there;
	if (!File.Exists(logPath)) {
		using (StreamWriter sw = new StreamWriter(logPath)) {
			sw.Close();
		}
	}

	using (StreamWriter sw = new StreamWriter(logPath, false, Encoding.Default)) {
		sw.Write(ExecuteSql());
		sw.Close();
	}

	Response.Clear();
	Response.AddHeader("content-disposition", "attachment;filename=" + logFile);
	Response.ContentType = "text/plain";
	Response.WriteFile(logPath);
	Response.End();

    }

    private string ExecuteSql() {
        ConnectionManager cn = new ConnectionManager();
        SqlConnection conn = cn.GetSqlConnection();
        SqlCommand tsql = conn.CreateCommand();

        tsql.CommandType = CommandType.Text;
        tsql.CommandText = "spGetRoutage";

        FDCLogger.LogEvent("Preparing to execute SQL statement: " + tsql.CommandText, source, 1);

        conn.Open();
        StringBuilder file = new StringBuilder();
        string[] a_row;

		int c_count = 0;
        using (SqlDataReader r = tsql.ExecuteReader()) {
            while (r.Read()) {
				c_count = r.FieldCount;
                a_row = new string[c_count];
                for (int i = 0; i < c_count; i++) {
                    //a_row[i] = "\"" + r.GetValue(i).ToString().Replace("\"", "\"\"") + "\"";
					a_row[i] = r.GetValue(i).ToString();
                }
                file.AppendLine(string.Join(" $ ", a_row));
            }
        }
        conn.Close();
        return file.ToString();
    }
</script>
<body></body>
</html>
